//
//  PersonEditVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/11/28.
//

import Foundation
import UIKit

class PersonEditVC: SubLevelViewController {
    let editV = PersonEditView()

    var modal: PersonModal!
    
    var param: UpOrSaveInfoParam!

    init(withModal _modal: PersonModal) {
        super.init(nibName: nil, bundle: nil)
        self.modal = _modal
        self.param = UpOrSaveInfoParam(withModal: _modal)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "人员详情"
        view.backgroundColor = .bg
        
        setupUI()
        
        editV.updateUI(withParam: param)
        
        reloadData()
    }
    
    func reloadData() {
        API.getPeopleInfo(withParam: PersonInfoParam(userId: String(modal.userId ?? -1))) { responseModel in
            if responseModel.errorCode == .Success {
                self.modal = responseModel.model
                self.param = UpOrSaveInfoParam(withModal: self.modal)
                self.editV.updateUI(withParam: self.param)
            }
        }
    }
    
    @objc func confrimTapped() {
        view.showToastActivity()
        
        param.nickName = editV.nameItem.value
        param.company = editV.companyItem.value
        param.phonenumber = editV.phoneItem.value
        param.idcard = editV.cardItem.value
        param.baidcard = editV.otherCardItem.value

        upload(withImg: editV.cardPhotoItem.image) { imgUrl1 in
            self.param.zjzp = imgUrl1
            self.upload(withImg: self.editV.otherCardPhotoItem.image) { imgUrl2 in
                self.param.bazfj = imgUrl2
                self.didSave()
            }
        }
    }
    
    func didSave() {
        do {
            let data: Data = try JSONEncoder().encode(param)
            let string = String(data: data, encoding: String.Encoding.utf8)
            API.postUpOrSaveInfo(withParam: CommonJsonParam(jsonStr: string)) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                    self.navigationController?.popViewController(animated: true)
                }
            }
        } catch {
            view.hideToastActivity()
            print("InfraredArmVC didValidated error", error)
        }
    }
    
    func upload(withImg vimg: UIImage?, completion: ((_ imgUrl: String?) -> Void)? = nil) {
        if let img = vimg {
            if let v1Path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img) {
                API.profileUpload(withImage: v1Path) { responseModel in
                    completion?(responseModel.model?.imgUrl)
                }
            } else {
                completion?(nil)
            }
        } else {
            completion?(nil)
        }
    }
    
    // MARK: - Setup
    
    func setupUI() {
        editV.submitBtn.addTarget(self, action: #selector(confrimTapped), for: .touchUpInside)
        view.addSubview(editV)
        editV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}
